package com.astrob.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * 写对象到文件中
 * */
public class WriteObjectsToFile<T> {

	public WriteObjectsToFile() {
	}

	/**
	 * Write Objects Array to File
	 * 
	 * @param szFilePath
	 *            [in] file path
	 * @param objs
	 *            [in] objects to write
	 * @return void
	 * **/
	public void onWriteObjects(final String szFilePath, final T[] objs) {

		if (null == szFilePath || null == objs)
			return;

		File file = new File(szFilePath);
		if (file.exists())
			file.delete();

		try {
			ObjectOutputStream objOutPutStream = new ObjectOutputStream(
					new FileOutputStream(file));
			for (Object obj : objs)
				objOutPutStream.writeObject(obj);
			objOutPutStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Write Objects Array to File
	 * 
	 * @param szFilePath
	 *            [in] file path
	 * @param objsList
	 *            [in] objects list to write
	 * @return void
	 * **/

	@SuppressWarnings("unchecked")
	public void onWriteObjects(final String szFilePath,
			final ArrayList<T> objsList) {

		if (null == szFilePath || null == objsList)
			return;
		onWriteObjects(szFilePath, (T[]) objsList.toArray());
	}
}
